package servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import util.JsonUtil;



public class AddFileInNewsServlet
    extends HttpServlet {

  private static final long serialVersionUID = -1403107155781623883L;
  private static Logger logger = Logger.getLogger(AddFileInNewsServlet.class);

  protected void doGet(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException,
      IOException {
	  doPost(request,response);
  }

  protected void doPost(HttpServletRequest request,
                        HttpServletResponse response) throws ServletException,
                        IOException {
	  request.setCharacterEncoding("utf-8");
	  response.setContentType("text/html;charset=utf-8");
	  try {
		  MultipartResolver resolver = new CommonsMultipartResolver(
				  getServletContext());
		  if (!resolver.isMultipart(request)) {
			  throw new ServletException("Not support none multipart request");
		  }
		  MultipartHttpServletRequest multiperHttpServletRequest = resolver.resolveMultipart(request);
		  String fileIdsStr = null;
		  String type = multiperHttpServletRequest.getParameter("type");//ckeditor上传的文件类型，有file,image,flash
		  String ckid = multiperHttpServletRequest.getParameter("CKEditor");//获取ckeditor里的控件ID
		  if(ckid==null){//没有，则表示非CKEditor
			  fileIdsStr = multiperHttpServletRequest.getParameter("fileIdsStr");
		  }
		  String fileNamesStr = "";
		  String uploadInstance = multiperHttpServletRequest.getParameter("upload_instance");
		  logger.info("uploadInstance  "+uploadInstance);
		  String fileIdArr[] = (fileIdsStr!=null)?fileIdsStr.split(","):null;
		  List fileList = new ArrayList();
		  Map fileMap = null;
		  MultipartFile item = null;
		  Iterator itor = multiperHttpServletRequest.getFileNames();
		  int i = 0;
		  while (itor.hasNext()) {
			  String fileName = (String) itor.next();

			  item = multiperHttpServletRequest.getFile(fileName);
			  if (!item.isEmpty()) {
				  fileMap = processUploadedFile(multiperHttpServletRequest
						  .getFile(fileName), (ckid==null)?fileIdArr[i++]:null,uploadInstance);
				  if (!fileMap.isEmpty()) {
					  fileList.add(fileMap);
					  fileNamesStr = (String) fileMap.get("fileName");
				  }
			  }
		  }
		  resolver.cleanupMultipart(multiperHttpServletRequest);

		  String eomsDocPath = fileMap.get("tempFileName")+"";
		  
		  PrintWriter out = null;
			// 在try-catch中把JSON数组写到response输出流
			try {
				out = response.getWriter();
				// 返回给page
				out.write(eomsDocPath.toString());
			} catch (IOException e) {
				e.printStackTrace();
			}
			// 最后，把流关闭
			finally {
				try {
					if (out != null) {
						out.close();
					}
				} catch (Exception e) {
				}
			}
	  }catch (Exception e) {
		  e.printStackTrace();
	  }
  }

  protected Map processUploadedFile(MultipartFile item, String fileId,String uploadInstance) throws Exception {

    Map fileMap = new HashMap();

    String contentType = item.getContentType();
    long size = item.getSize();
    String fileName = item.getOriginalFilename();
    SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmss");
    StringBuffer postfix = new StringBuffer(256);
    StringBuffer prefix = new StringBuffer(32);
    prefix.append(s.format(new Date())).append('-');

    File f = null;
    String rootPath ="";
    String eomsDocPath =""+uploadInstance;
    
    try { 
       String path = getServletContext().getRealPath("/")+ "/download";
       System.out.println(path);
      //}   	
      System.out.println("eomsDocPath------------------------------>>  "+eomsDocPath);
      f = File.createTempFile(prefix.toString(), postfix.toString(),
                              new File(eomsDocPath));
    }
    catch (IOException ex) {
      ex.printStackTrace();
      return Collections.EMPTY_MAP;
    }
    String tempFileName = f.getName();
    try {
      item.transferTo(f);
    }
    catch (Exception e) {
      e.printStackTrace();
      return Collections.EMPTY_MAP;
    }

    fileMap.put("contentType", contentType);
    fileMap.put("size", new Long(size));
    fileMap.put("fileName", fileName);
    fileMap.put("tempFileName", tempFileName);
    fileMap.put("fileKey", "");
    fileMap.put("eomsDocPath", "http://10.229.19.33:8081");
    return fileMap;
  }
}
